package com.spider.lwlk.mongodb.task


import com.spider.lwlk.mongodb.task.taskstatus.TaskStatus
import com.spider.lwlk.mongodb.workplace.Mongo
import groovyx.net.http.HTTPBuilder

import static groovyx.net.http.ContentType.TEXT
import static groovyx.net.http.Method.GET

class BaseTask {

    String path

    TaskStatus taskStatus = TaskStatus.Waiting

    final doGet() {

        def http = new HTTPBuilder()

        http.request(path, GET, TEXT, onRequest())

        this
    }

    final doUpdate() {

        try {

            Mongo.withInstance(onFilter())

            Mongo.withInstance(onUpdate())

            Mongo.withInstance(onCompleted())
        }

        catch (Exception e) {

            doExceptionLog([ path: path, cause: 'exception', time: Calendar.getInstance().getTimeInMillis(), msg: e.getStackTrace().join('\n')])
        }
    }

    final doExceptionLog(def args) { Mongo.withInstance(onException(args)) }

    final isCompleted() { taskStatus == TaskStatus.Success }

    final onRequest() {

        {   req ->

            uri.path = path

            uri.query = [:]

            headers.'User-Agent' = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"

            headers.Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'

            response.success = onSuccess()

            response.failure = onFailure()
        }
    }

    def onSuccess() { { resp, reader -> taskStatus = TaskStatus.RequestSuccess } }

    def onFailure() {

        {   resp ->

            taskStatus = TaskStatus.RequestFailure

            doExceptionLog([ path: path, cause: 'failure', code: resp.statusLine.statusCode, reason: resp.statusLine.reasonPhrase ])
        }
    }

    def onFilter() { {  -> } }

    def onUpdate() { {  -> taskStatus = TaskStatus.UpdateSuccess } }

    def onCompleted() { {  -> taskStatus = TaskStatus.Success } }

    def onException(def args) { { -> taskStatus = TaskStatus.UpdateFailure; db.exception.insert(args) } }
}
